import React from 'react';
import { useDrop } from 'react-dnd';
import { useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil'
import { designerState } from '../../../store'
import Render from '../Render'
import SelectedMenu from '../SelectedMenu'
import { produce } from 'immer';
import { nanoid } from 'nanoid'

import ColScheme from '../../component/layout/Col/scheme'

import DropWrapper from '../DropWrapper';

import { ConfigProvider } from 'antd';
import enUS from 'antd/lib/locale/en_US';
import zhCN from 'antd/lib/locale/zh_CN';

import { DRAG_TYPE } from '../drag_type'

import './index.less'

interface IProps {
  children?: any
}

export default function Canvas (props: IProps) {
  const [pageData, setPageData] = useRecoilState(designerState.pageDataAtom);
  const layoutData = useRecoilValue(designerState.getPageDataByParent(null));
  const setSelectedNode = useSetRecoilState(designerState.selectedNodeAtom)

  const [ collected, drop ] = useDrop({
    accept: DRAG_TYPE.layout,
    drop: (item: any, monitor) => {
      console.log('canvas-drop', item)

      item = produce(item, (draft: any) => {
        // 拖放生效时，重置id
        draft.meta.id = nanoid()
      })
      setPageData((pageData: Array<any>) => [
        ...pageData, item
      ])
      
      // 第一次拖放，给 selectedNode 赋值
      if (pageData.length === 0) {
        setSelectedNode(item)
      }

      if (item.meta.name === 'Row') {
        // 处理行布局
        // 计算行中的列数
        for (let i = 0; i < item.config.attr.cols; i++) {
          var colItem = produce(ColScheme, (draft: any) => {
            draft.meta.id = nanoid()
            draft.meta.parent = item.meta.id // 设置父 Id
          })
          // console.log('newItem', newItem)
          setPageData((pageData: Array<any>) => [
            ...pageData, colItem
          ])
        }
      } else if (item.meta.name === 'Tab') {
        // 处理 Tab 布局
      }
     
      // 如果是画布中已存在的则不新增考虑只改变顺序
      // if (item.meta.key) {
      //   return
      // } else {
      //   // var newItem = {...item, parent: null}
      //   // RecoilDataUtil(pageData, setPageData).add(newItem)
      // }
    },
    collect: (monitor) => {
      return {
        isOver: monitor.isOver(),
        canDrop: monitor.canDrop(),
      }
    },
  })

  // ConfigProvider.config({
  //   prefixCls: 'custom',
  //   theme: {
  //     primaryColor: theme,
  //   },
  // });

  const isActive = collected.canDrop && collected.isOver
  const bg = isActive ? '#d9a7d9' : '#d9d9d9';

  return (
    <div className='canvas-ctn' >
      <Render pageData={ layoutData } noDrop />
      
      <div ref={ drop } className="canvas-drop-area" style={{ background: bg }}>
        + 拖拽到这里
      </div>

      <SelectedMenu />
    </div>
  )
}
